package cn.lcfms.app.index.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.http.HttpServletResponse;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.lcfms.app.BaseController;
import cn.lcfms.bin.core.Application;
import cn.lcfms.cms.Plagiarism;
import cn.lcfms.utils.FlagWebsocket;
import net.sf.json.JSONObject;

@Controller("index.LcfmsController")
@RequestMapping("/index/lcfms")
public class LcfmsController extends BaseController{
	
	
	private boolean onflag=false;
	
	
	@RequestMapping("/init.html")
	public String init() {		
		return "lcfms/fzmain";
	}
	
	@RequestMapping("/postfz")
	public String postfz(String url,String charset,String extra,String cookie,String filename){
		if(onflag) {
			return "{code:0}";
		}
		onflag=true;
		try {
			URL u = new URL(url);
			String host = u.getHost();
			Plagiarism plag=new Plagiarism(url,charset,cookie,Application.ROOT_PATH+"flag"+Application.F+host+Application.F+filename+".html", Application.ROOT_PATH+"flag"+Application.F+host,"html");
			plag.setTypeHtml();
			if(extra!=null && !extra.equals("")) {
				plag.setImgcode(extra);
			}
			String error;
			if((error=plag.getError())!=null) {
				FlagWebsocket.echo(false,error,100);
				onflag=false;
				return "{code:0}";
			}
			Timer timer=new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {		
					String error;
					while ((error=plag.getError())==null) {	
						int act = plag.getAct();					
						if(act==100) {
							break;		
						}
					}
					if(error!=null) {
						FlagWebsocket.echo(false,error,100);
					}else {
						JSONObject object=new JSONObject();
						object.put("filename", filename);
						object.put("host", host);
						FlagWebsocket.echo(true,object.toString(),100);
					}	
					onflag=false;
				}
			}, 200);
		} catch (Exception e) {
			FlagWebsocket.echo(false,"url解析异常",100);
			onflag=false;
			e.printStackTrace();
		}
		return "{code:1}";
	}
	
	@RequestMapping("/fz")
	public String fz() {
		if(onflag) {
			return "lcfms/fm";
		}
		return "lcfms/fz";
	}
	
	
	@RequestMapping("/download")
	public void download(String host,HttpServletResponse response) throws IOException {
		String path=Application.ROOT_PATH+"flag"+Application.F+host;
		compressExe(path+File.separator+host+".zip",path);
		InputStream inStream = new FileInputStream(path+File.separator+host+".zip");
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + host+".zip\"");
        byte[] b = new byte[1024];
        int len;
        while ((len = inStream.read(b)) > 0){
        	 response.getOutputStream().write(b, 0, len);
        }
        inStream.close(); 
        deleteDir(new File(path)); 		
	}
	
	
	@RequestMapping("/check")
	@ResponseBody
	public String check(boolean stop){
		if(stop) {
			onflag=false;
		}
		return onflag+"";
	}
			
	private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
	
	private void compressExe(String zipFile, String dir) {    
		Zip zip = new Zip();  
	    zip.setBasedir(new File(dir));  
	    zip.setDestFile(new File(zipFile));  
	    Project p = new Project();   
	    zip.setProject(p);  
	    zip.execute();     
    }    
	
	public static void main(String[] args) throws MalformedURLException {
		File file=new File("D:\\javaproject\\lcfms 5.4");
		show(file);
		
	}
	
	public static void show(File file) {
		if(file.isDirectory()) {
			File[] list = file.listFiles();
			if(list.length==0) {
				System.out.println(file.getPath());
			}else {
				for(File f:list) {
					show(f);
				}
			}		
		}
	}
		
}
